package com.chpro.common;

import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.chpro.common.Lang;

import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Phrase;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

public class PdfUtil {

    private static BaseFont cnBaseFont = null;
    private static Font cnFont = new Font(cnBaseFont,10,Font.NORMAL,Color.BLUE);	//标题font

    private static Font fontChinese =  new  Font(cnBaseFont);	//内容font


    static{
        try {
            cnBaseFont = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",false);
        } catch (DocumentException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }
    }

    public static void exportPdf(List<Map<String,Object>> list,OutputStream out) throws Exception {



        String[] headers = Lang.getStringArray(list.get(0).keySet().toArray());	//标题头


        Table table = new Table(headers.length);
        table.setWidth(80);
        table.setBorder(1);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

        //设置列头

        for(String s:headers){
            table.addCell(buildFontCell(s,cnFont));
        }

        //设置内容

        for(Map<String,Object> map:list){
            for(String s:headers){
                table.addCell(new Phrase(String.valueOf(map.get(s)),fontChinese));
            }
        }

        //生成文档

        Document document = new Document();
        PdfWriter.getInstance(document,out);
        document.open();
        document.add(table);
        document.close();

    }

    private static Cell buildFontCell(String content,Font font){
        try{
            Phrase phrase = new Phrase(content,font);
            return new Cell(phrase);
        }catch(Exception e){
            throw new RuntimeException();
        }
    }

}